﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsJobTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// WatchList Business Object
    /// </summary>

    public class WatchList : BOBase
    {

        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected WatchList() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the WatchList.
        /// </summary>
        public int UserID_RK_RegisteredUserID
        {
            get { return _userID_RK_RegisteredUserID; }
            set
            {
                if (_userID_RK_RegisteredUserID != value)
                {
                    if (OnPropertyChanging("UserID_RK_RegisteredUserID", _userID_RK_RegisteredUserID, value))
                    {
                        int oldValue = _userID_RK_RegisteredUserID;
                        _userID_RK_RegisteredUserID = value;

                        OnPropertyChanged("UserID_RK_RegisteredUserID", oldValue, value);
                    }
                }
            }
        }  private int _userID_RK_RegisteredUserID = -1;

        /// <summary>
        /// JobID_RK_Jobs.
        /// </summary>
        public string JobID_RK_Jobs
        {
            get { return _jobID_RK_Jobs; }
            set
            {
                if (_jobID_RK_Jobs != value)
                {
                    if (OnPropertyChanging("JobID_RK_Jobs", _jobID_RK_Jobs, value))
                    {
                        string oldValue = _jobID_RK_Jobs;
                        _jobID_RK_Jobs = value;
                        OnPropertyChanged("JobID_RK_Jobs", oldValue, value);
                    }
                }
            }
        }  private string _jobID_RK_Jobs = null;


        /// <summary>
        /// Comment.
        /// </summary>
        public string Comment
        {
            get { return _comment; }
            set
            {
                if (_comment != value)
                {
                    if (OnPropertyChanging("Comment", _comment, value))
                    {
                        string oldValue = _comment;
                        _comment = value;
                        OnPropertyChanged("Comment", oldValue, value);
                    }
                }
            }
        }  private string _comment = null;



        /// <summary>
        /// Date/time at which the Job was added to watchlist.
        /// </summary>
        public DateTime? AddedDate
        {
            get { return _addedDate; }
            set
            {
                if (_addedDate != value)
                {
                    if (OnPropertyChanging("AddedDate", _addedDate, value))
                    {
                        DateTime? oldValue = _addedDate;
                        _addedDate = value;
                        OnPropertyChanged("AddedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _addedDate = null;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty WatchList object.
        /// </summary>
        public static WatchList CreateNew()
        {
            WatchList obj = new WatchList();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.AddedDate = DateTime.Now;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static WatchList CreateNew(WatchListCollection collection)
        {
            WatchList obj = CreateNew();

            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllWatchListByUserID

        /// <summary>
        /// Returns a collection of all WatchList.
        /// </summary>
        public static WatchListCollection GetAllWatchListByUserID(int userid)
        {
            WatchListTableAdapter adapter = new WatchListTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsJob.WatchListDataTable tbl = adapter.GetData(userid);

            WatchListCollection list = new WatchListCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsJob.WatchListRow row in tbl.Rows)
                {
                    WatchList watchlist = new WatchList();
                    RelationalToObject(watchlist, row);
                    list.Add(watchlist);
                }
            }

            return (list);
        }

        #endregion

        #region GetWatchListByUserID_JobID

        /// <summary>
        /// Returns a collection of all WatchList to check for duplicacy.
        /// </summary>
        public static WatchListCollection GetWatchListByUserID_JobID(int userid, string jobid)
        {
            WatchListTableAdapter adapter = new WatchListTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsJob.WatchListDataTable tbl = adapter.GetDataByUserIDandJobID(userid,jobid);

            WatchListCollection list = new WatchListCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsJob.WatchListRow row in tbl.Rows)
                {
                    WatchList watchlist = new WatchList();
                    RelationalToObject(watchlist, row);
                    list.Add(watchlist);
                }
            }

            return (list);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified WatchList.
        /// </summary>
        public static void Update(WatchList obj)
        {
            bool updateWatchList = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateWatchList = (obj.ObjState != ObjectState.Unchanged);

                if (!updateWatchList)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsJob.WatchListDataTable tbl = null;
            if (updateWatchList)
            {
                WatchListTableAdapter adapter = new WatchListTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsJob.WatchListDataTable();
                dsJob.WatchListRow row = tbl.NewWatchListRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("WatchListID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("WatchList: UserID_RK_RegisteredUserID={0}, JobID_RK_Jobs={1}, {2}", UserID_RK_RegisteredUserID, JobID_RK_Jobs, Comment));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more WatchList objects.
    /// </summary>

    public class WatchListCollection : List<WatchList>
    {
        #region Types

        public class UserComparer : IComparer<WatchList>
        {
            public int Compare(WatchList wl1, WatchList wl2)
            {
                return (String.Compare(wl1.JobID_RK_Jobs, wl1.JobID_RK_Jobs));
            }
        }

        #endregion

        #region Public Methods

        #region FindByWatchListUserID

        public WatchList FindByWatchListUserID(int userID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].UserID_RK_RegisteredUserID == userID)
                    return (this[ndx]);

            return (null);
        }

        #endregion


        #endregion
    }
}
